<template>
  <div class="purchase-return-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="退货单编号">
          <el-input v-model="searchForm.returnCode" placeholder="请输入退货单编号" clearable />
        </el-form-item>
        <el-form-item label="退货单名称">
          <el-input v-model="searchForm.returnName" placeholder="请输入退货单名称" clearable />
        </el-form-item>
        <el-form-item label="采购订单编号">
          <el-input v-model="searchForm.purchaseCode" placeholder="请输入采购订单编号" clearable />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="operation-btns">
        <el-button type="success" @click="handleAdd">+ 新增</el-button>
        <el-button type="danger" @click="handleDelete" :disabled="!multipleSelection.length">删除</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      highlight-current-row
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="returnCode" label="退货单编号" min-width="120" />
      <el-table-column prop="returnName" label="退货单名称" min-width="120" />
      <el-table-column prop="purchaseCode" label="采购订单编号" min-width="120" />
      <el-table-column prop="supplierCode" label="供应商编码" min-width="100" />
      <el-table-column prop="supplierName" label="供应商名称" min-width="150" />
      <el-table-column prop="returnDate" label="退货日期" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.returnDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="单据状态" min-width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="waybillnumber" label="运单号" min-width="120" />
      <el-table-column prop="contactperson" label="联系人" min-width="100" />
      <el-table-column prop="desc" label="备注" min-width="150" />
      <el-table-column label="操作" width="320" fixed="right">
        <template #default="scope">
          <el-button
            v-if="Number(scope.row.status) === 1"
            type="primary"
            link
            size="small"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            v-if="Number(scope.row.status) === 1"
            type="success"
            link
            size="small"
            @click="handleExecute(scope.row)"
          >执行拣货</el-button>
          <el-button
            v-if="Number(scope.row.status) === 2"
            type="warning"
            link
            size="small"
            @click="handleOutStock(scope.row)"
          >执行出库</el-button>
          <el-button
            v-if="Number(scope.row.status) !== 4 && Number(scope.row.status) !== 3"
            type="danger"
            link
            size="small"
            @click="handleCancel(scope.row)"
          >取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialogVisible" :title="isEdit ? '编辑采购退货' : '添加采购退货'" width="800px" @close="resetAddForm">
      <el-form :model="addForm" label-width="110px" :rules="addFormRules" ref="addFormRef" :inline="true">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="退货单编号" prop="returnCode" required>
              <el-input v-model="addForm.returnCode" placeholder="请输入退货单编号" :disabled="addForm.autoCode" />
              <el-switch v-model="addForm.autoCode" style="margin-left: 10px;" active-text="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货单名称" prop="returnName" required>
              <el-input v-model="addForm.returnName" placeholder="请输入退货单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购订单编号" prop="purchaseCode">
              <el-input v-model="addForm.purchaseCode" placeholder="请输入采购订单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName" required>
              <el-input v-model="addForm.supplierName" placeholder="请选择供应商" readonly style="width: 100%;">
                <template #append>
                  <el-button :icon="Search" @click="showSupplierDialog = true"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货日期" prop="returnDate" required>
              <el-date-picker v-model="addForm.returnDate" type="date" placeholder="请选择退货日期" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货原因" prop="reason">
              <el-input v-model="addForm.reason" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运单号" prop="waybillnumber">
              <el-input v-model="addForm.waybillnumber" placeholder="请输入运单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactperson">
              <el-input v-model="addForm.contactperson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="desc">
              <el-input v-model="addForm.desc" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleAddSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 供应商选择弹窗 -->
    <el-dialog v-model="showSupplierDialog" title="供应商选择" width="900px">
      <el-form :inline="true" :model="supplierSearchForm" class="search-form" style="margin-bottom: 10px;">
        <el-form-item label="供应商编码">
          <el-input v-model="supplierSearchForm.code" placeholder="请输入供应商编码" />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="supplierSearchForm.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchSupplierList">搜索</el-button>
          <el-button @click="resetSupplierSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="supplierList" v-loading="supplierLoading" style="width: 100%; margin-top: 10px;" @row-dblclick="selectSupplier">
        <el-table-column prop="supplierCode" label="供应商编码" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="180" />
        <el-table-column prop="supplierPhone" label="电话" width="140" />
        <el-table-column prop="supplierAddress" label="地址" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="selectSupplier(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="supplierPage.page"
          v-model:page-size="supplierPage.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="supplierPage.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierPageChange"
        />
      </div>
      <template #footer>
        <el-button @click="showSupplierDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import axios from 'axios';
import { Search } from '@element-plus/icons-vue';

// 数据类型定义
interface PurchaseReturn {
  id: number;
  returnCode: string;
  returnName: string;
  purchaseCode: string;
  supplierCode: string;
  supplierName: string;
  returnDate: string;
  status: string;
  waybillnumber: string;
  contactperson: string;
  desc: string;
  orderField?: string;
  orderType?: number;
}

// 搜索表单
const searchForm = reactive({
  returnCode: '',
  returnName: '',
  purchaseCode: '',
  supplierName: '',
  orderField: '',
  orderType: ''
});

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 表格相关
const tableData = ref<PurchaseReturn[]>([]);
const loading = ref(false);
const selectedRow = ref<PurchaseReturn | null>(null);
const multipleSelection = ref<PurchaseReturn[]>([]);
const tableRef = ref();

// 新增相关
const addDialogVisible = ref(false);
const addFormRef = ref<FormInstance>();
const isEdit = ref(false);
const addForm = reactive({
  id: 0,
  returnCode: '',
  autoCode: false,
  returnName: '',
  purchaseCode: '',
  supplierName: '',
  supplierCode: '',
  returnDate: '',
  reason: '',
  waybillnumber: '',
  contactperson: '',
  desc: '',
  status: '1' // 默认为草稿状态
});
const addFormRules = {
  returnName: [{ required: true, message: '请输入退货单名称', trigger: 'blur' }],
  supplierName: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
  returnDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }]
};

// 供应商相关
const showSupplierDialog = ref(false);
const supplierAllList = ref<any[]>([]); // 全部数据
const supplierList = ref<any[]>([]);    // 当前页数据
const supplierLoading = ref(false);
const supplierSearchForm = reactive({ code: '', name: '' });
const supplierPage = reactive({ page: 1, pageSize: 5, total: 0 });

// 监听autoCode变化，自动生成编号
watch(() => addForm.autoCode, (val) => {
  if (val) {
    addForm.returnCode = generateAutoCode();
  } else {
    addForm.returnCode = '';
  }
});

// 弹窗打开时只请求一次全部数据
watch(showSupplierDialog, async (val) => {
  if (val) {
    supplierLoading.value = true;
    try {
      const res = await axios.get('/api/MasterData/GetAllSupplierList');
      if (Array.isArray(res.data)) {
        supplierAllList.value = res.data;
      } else if (res.data && Array.isArray(res.data.data)) {
        supplierAllList.value = res.data.data;
      } else {
        supplierAllList.value = [];
      }
      supplierPage.page = 1;
      filterAndPaginateSupplier();
    } catch (e) {
      supplierAllList.value = [];
      supplierList.value = [];
      supplierPage.total = 0;
      ElMessage.error('获取供应商失败');
    } finally {
      supplierLoading.value = false;
    }
  }
});

// 前端搜索和分页
function filterAndPaginateSupplier() {
  let filtered = supplierAllList.value;
  if (supplierSearchForm.code) {
    filtered = filtered.filter(item =>
      (item.supplierCode || '').toLowerCase().includes(supplierSearchForm.code.toLowerCase())
    );
  }
  if (supplierSearchForm.name) {
    filtered = filtered.filter(item =>
      (item.supplierName || '').toLowerCase().includes(supplierSearchForm.name.toLowerCase())
    );
  }
  supplierPage.total = filtered.length;
  const start = (supplierPage.page - 1) * supplierPage.pageSize;
  const end = start + supplierPage.pageSize;
  supplierList.value = filtered.slice(start, end);
}

const fetchSupplierList = () => {
  supplierPage.page = 1;
  filterAndPaginateSupplier();
};

const resetSupplierSearch = () => {
  supplierSearchForm.code = '';
  supplierSearchForm.name = '';
  supplierPage.page = 1;
  filterAndPaginateSupplier();
};

// 分页切换
const handleSupplierPageChange = (val: number) => {
  supplierPage.page = val;
  filterAndPaginateSupplier();
};
const handleSupplierSizeChange = (val: number) => {
  supplierPage.pageSize = val;
  supplierPage.page = 1;
  filterAndPaginateSupplier();
};

function generateAutoCode() {
  const now = new Date();
  const yyyy = now.getFullYear();
  const mm = String(now.getMonth() + 1).padStart(2, '0');
  const dd = String(now.getDate()).padStart(2, '0');
  const rand = Math.floor(Math.random() * 900) + 100; // 三位随机数
  return `CGTH${yyyy}${mm}${dd}${rand}`;
}

function selectSupplier(row: any) {
  addForm.supplierName = row.supplierName;
  addForm.supplierCode = row.supplierCode;
  showSupplierDialog.value = false;
}

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await axios.get('http://localhost:9991/api/WarehouseManagement/GetPurchaseReturns', {
      params: {
        returnCode: searchForm.returnCode,
        returnName: searchForm.returnName,
        purchaseCode: searchForm.purchaseCode,
        supplierName: searchForm.supplierName,
        page: pagination.page,
        pageSize: pagination.pageSize
      }
    });

    if (response.data && (response.data.status === 0 || response.data.success)) {
      tableData.value = response.data.rows || response.data.data || [];
      pagination.total = response.data.total || 0;
    } else {
      ElMessage.error(response.data?.msg || '获取数据失败');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchForm.returnCode = '';
  searchForm.returnName = '';
  searchForm.purchaseCode = '';
  searchForm.supplierName = '';
  searchForm.orderField = '';
  searchForm.orderType = '';
  pagination.page = 1;
  fetchData();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.page = 1;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  pagination.page = val;
  fetchData();
};

// 行选择
const handleSelectionChange = (selection: PurchaseReturn[]) => {
  multipleSelection.value = selection;
  selectedRow.value = selection.length > 0 ? selection[0] : null;
};

const handleRowClick = (row: PurchaseReturn) => {
  selectedRow.value = row;
  
  // 单击行时不再清除已有选择，只切换当前行的选中状态
  if (tableRef.value) {
    tableRef.value.toggleRowSelection(row);
  }
};

// 操作方法
const handleAdd = () => {
  isEdit.value = false;
  resetAddForm();
  addDialogVisible.value = true;
};

const handleEdit = (row: PurchaseReturn) => {
  isEdit.value = true;
  Object.assign(addForm, row);
  addDialogVisible.value = true;
};

const handleDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请先选择要删除的记录');
    return;
  }
  
  // 检查所有选中记录的状态是否为草稿(1)
  const nonDraftItems = multipleSelection.value.filter(item => Number(item.status) !== 1);
  if (nonDraftItems.length > 0) {
    ElMessage.warning('只能删除状态为草稿的退货单，请重新选择');
    return;
  }
  
  // 获取选中项的ID数组
  const selectedIds = multipleSelection.value.map(item => item.id);
  const itemCount = multipleSelection.value.length;
  
  const confirmMessage = itemCount === 1 
    ? `确定要删除退货单 ${multipleSelection.value[0].returnCode} 吗？` 
    : `确定要删除选中的 ${itemCount} 个退货单吗？`;
  
  ElMessageBox.confirm(confirmMessage, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post('/api/WarehouseManagement/BatchDeletePurchaseReturn', selectedIds);
      if (response.data && (response.data.status === true || response.data.success === true)) {
        ElMessage.success(`成功删除 ${itemCount} 条记录`);
        fetchData();
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {});
};

const handleExecute = (row: PurchaseReturn) => {
  ElMessageBox.confirm('确定要执行拣货操作吗？', '执行拣货', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 用URL参数方式传递
      const response = await axios.post(`/api/WarehouseManagement/UpdatePurchaseReturnStates?id=${row.id}&states=2`);
      console.log('UpdatePurchaseReturnStates 返回:', response.data);
      if (response.data && (response.data.status === true || response.data.success === true)) {
        ElMessage.success('拣货操作成功，状态已更新为待拣货');
        fetchData();
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '操作失败');
      }
    } catch (error) {
      console.error('执行拣货失败:', error);
      ElMessage.error('执行拣货失败，请稍后重试');
    }
  }).catch(() => {});
};

const handleOutStock = (row: PurchaseReturn) => {
  ElMessageBox.confirm('确定要执行出库操作吗？', '执行出库', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 用URL参数方式传递
      const response = await axios.post(`/api/WarehouseManagement/UpdatePurchaseReturnStates?id=${row.id}&states=3`);
      console.log('UpdatePurchaseReturnStates 返回:', response.data);
      if (response.data && (response.data.status === true || response.data.success === true)) {
        ElMessage.success('出库操作成功，状态已更新为已完成');
        fetchData();
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '操作失败');
      }
    } catch (error) {
      console.error('执行出库失败:', error);
      ElMessage.error('执行出库失败，请稍后重试');
    }
  }).catch(() => {});
};

const handleCancel = (row: PurchaseReturn) => {
  ElMessageBox.confirm('确定要取消该单据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 用URL参数方式传递
      const response = await axios.post(`/api/WarehouseManagement/UpdatePurchaseReturnStates?id=${row.id}&states=4`);
      console.log('UpdatePurchaseReturnStates 返回:', response.data);
      if (response.data && (response.data.status === true || response.data.success === true)) {
        ElMessage.success('单据已取消');
        fetchData();
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '取消失败');
      }
    } catch (error) {
      console.error('取消单据失败:', error);
      ElMessage.error('取消单据失败，请稍后重试');
    }
  }).catch(() => {});
};

const handleAddSave = () => {
  addFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await axios.post('/api/WarehouseManagement/UpdatePurchaseReturn', addForm);
        ElMessage.success('修改成功');
      } else {
        await axios.post('/api/WarehouseManagement/AddPurchaseReturn', addForm);
        ElMessage.success('添加成功');
      }
      addDialogVisible.value = false;
      fetchData();
    } catch (e) {
      ElMessage.error('操作失败');
    }
  });
};

const resetAddForm = () => {
  Object.assign(addForm, {
    id: 0,
    returnCode: '',
    autoCode: false,
    returnName: '',
    purchaseCode: '',
    supplierName: '',
    supplierCode: '',
    returnDate: '',
    reason: '',
    waybillnumber: '',
    contactperson: '',
    desc: '',
    status: '1' // 默认为草稿状态
  });
  addFormRef.value?.clearValidate();
};

// 格式化方法
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
};

const getStatusText = (status: number | string) => {
  switch (Number(status)) {
    case 1: return '草稿';
    case 2: return '待拣货';
    case 3: return '已完成';
    case 4: return '已取消';
    default: return '未知';
  }
};

const getStatusType = (status: number | string) => {
  switch (Number(status)) {
    case 1: return 'info';
    case 2: return 'warning';
    case 3: return 'primary';
    case 4: return 'danger';
    default: return 'default';
  }
};

// 生命周期
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.purchase-return-container {
  padding: 20px;
}

.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 15px;
}

.operation-btns {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-dialog) {
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(0,0,0,0.12);
  background: #fcfcfe;
}
:deep(.el-dialog__header) {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  padding-top: 24px;
  padding-bottom: 12px;
  border-bottom: 1.5px solid #f2f3f5;
  letter-spacing: 1px;
}
:deep(.el-dialog__body) {
  padding: 36px 40px 18px 40px;
  background: #f8fafd;
}
:deep(.el-dialog__footer) {
  padding: 16px 40px 28px 40px;
  background: #f8fafd;
  border-top: 1.5px solid #f2f3f5;
  text-align: right;
}
:deep(.el-form-item) {
  margin-bottom: 28px !important;
}
:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 12px;
  background: #fff;
  font-size: 15px;
}
:deep(.el-form-item__label.is-required) {
  color: #f56c6c;
  font-weight: bold;
}
:deep(.el-form-item__label) {
  font-size: 16px;
  letter-spacing: 0.5px;
}
:deep(.el-button) {
  border-radius: 8px;
  font-size: 15px;
}

/* 供应商弹窗表格美化 */
:deep(.el-table th) {
  background: #f3f6fa;
  color: #222;
  font-weight: bold;
  font-size: 16px;
}
:deep(.el-table tr:hover) > td {
  background: #e6f7ff !important;
}
:deep(.el-table__body tr) {
  transition: background 0.2s;
}
:deep(.el-table__footer-wrapper) {
  background: #f8fafd;
}
:deep(.el-dialog__body .pagination-container) {
  margin-top: 32px;
}
</style>